package com.zoshine.zzg.config;

import com.zoshine.zzg.base.BaseException;
import com.zoshine.zzg.base.BaseResponse;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.exception.SysException;
import com.zoshine.zzg.respons.ErrResponse;
import org.apache.ibatis.binding.BindingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 控制器配置
 *
 * @author 贾俊峰
 * @version 1.0
 * @time 2017/1/7 13:12
 */
@ControllerAdvice
public class ControllerConfigurer {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 异常处理
     * 根据请求类型的不同,返回错误页面或包含错误信息的json串
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponse exceptionHandler(Exception ex) {
        boolean isAppException = false;
        BaseException exception;
        if (ex instanceof SysException) {
            exception = (SysException) ex;
        } else if (ex instanceof AppException) {
            isAppException = true;
            exception = (AppException) ex;
        } else if (ex instanceof HttpRequestMethodNotSupportedException) { // 请求类型错误
            isAppException = true;
            exception = new AppException(ErrorMessage.REQUEST_TYPE_ERROR);
        } else if (ex instanceof NullPointerException || ex instanceof ArrayIndexOutOfBoundsException
                || ex instanceof IOException) {
            exception = new SysException();// 系统错误
        } else if (ex instanceof BindingException) {
            exception = new SysException(ErrorMessage.DAO_BINDING_ERROR);
        } else {
            exception = new SysException(ErrorMessage.UNKNOWN_ERROR);// 未知错误
        }
        if (!isAppException) {//不打印应用异常
            logger.error("系统错误", ex);
        }

        return new ErrResponse(exception);

    }
}
